package band.wukong.practice.javase.core.io.standardio;

import java.io.*;

/**
 * Desc:
 * Author: sunjs
 * Date: 2009-11-17 17:28:34
 */
public class TestRedirect {
    //    private static final String FILE_IN = "E:\\workspace\\TestJava\\src\\com\\jsun\\javase\\io\\doc\\poem.txt";
    private static final String FILE_IN = "E:\\somecode\\TestJava\\src\\com\\jsun\\javase\\io\\doc\\poem.txt";
    //    private static final String FILE_OUT = "E:\\workspace\\TestJava\\src\\com\\jsun\\javase\\io\\doc\\out.txt";
    private static final String FILE_OUT = "E:\\somecode\\TestJava\\src\\com\\jsun\\javase\\io\\doc\\out.txt";
    //    private static final String FILE_ERR = "E:\\workspace\\TestJava\\src\\com\\jsun\\javase\\io\\doc\\err.txt";
    private static final String FILE_ERR = "E:\\somecode\\TestJava\\src\\com\\jsun\\javase\\io\\doc\\err.txt";

    /**
     * 为标准I/O重定向
     *
     * @param in
     * @param out
     * @param err
     */
    public static void redirect(InputStream in, PrintStream out, PrintStream err) {
        System.setIn(in);
        System.setOut(out);
        System.setErr(err);
    }

    /**
     * 把来自标准输出流的数据写到标准输出流和标准错误输出流
     *
     * @throws IOException
     */
    public static void copy() throws IOException {
        InputStreamReader reader = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(reader);
        String data;
        while (null != (data = br.readLine()) && data.length() != 0) {
            System.out.println(data);
            System.err.println(data);
        }
    }

    public static void main(String args[]) throws IOException {
        InputStream stdIn = System.in;
        PrintStream stdOut = System.out;
        PrintStream stdErr = System.err;

        InputStream in = new BufferedInputStream(new FileInputStream(FILE_IN));
        PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(FILE_OUT)));
        PrintStream err = new PrintStream(new BufferedOutputStream(new FileOutputStream(FILE_ERR)));

        redirect(in, out, err); //把标准I/O重定向到文件
        copy(); //把FILE_IN文件中的数据拷贝到FILE_OUT和FIFE_ERR中

        in.close();
        out.close();
        err.close();


        InputStream in2 = new BufferedInputStream(new FileInputStream(FILE_IN));
        redirect(in2, stdOut, stdErr);
        copy();
        in.close();

    }

}
